<template>
  <AdminLog/>
  <div id="log">
    <div class="layout">
        <el-tabs type="border-card" class="card">
            <el-tab-pane label="密码登录">
                <el-form label-position="right" label-width="60px" style="max-width: 570px" class="loginForm">
                    <el-form-item label="账户：" style="width: 310px; margin: 25px 0">
                        <el-input v-model="account" placeholder="用户名" @blur="judgeunph(account)" class="input"/>
                    </el-form-item>
                    <el-form-item label="密码：" style="width: 310px;">
                        <el-input type="password" v-model="password" placeholder="密码" @blur="judgepsd(password)" class="input"/>
                    </el-form-item>
                    <el-row>
                        <el-checkbox class="checkBox" v-model="isAgree" label="同意用户使用准则" name="type" />
                    </el-row>
                    <el-button text>
                        <a class="floatR" @click="isChangePassword = true" >忘记密码</a>
                    </el-button>
                    <el-button text>
                        <a class="floatR" @click="registerUser = true">注册</a>
                    </el-button><br>
                    <el-button v-if="isAgree" type="primary" class="loginBtn" @click="login"
                        style="width: 310px;text-align: center;">
                        登录
                    </el-button>
                </el-form>
            </el-tab-pane>

            <el-tab-pane label="验证码登录">
                <el-form label-position="right" label-width="100px" style="
                max-width: 460px" class="loginForm logcard">
                    <el-form-item label="手  机：" style="width: 345px;margin-left: -35px;">
                        <el-input v-model="phone" placeholder="手机号" style="margin-left: 10px;" />
                    </el-form-item>
                    <el-form-item label="验证码：" style="width: 345px;;margin-left: -25px;">
                        <el-row>
                            <el-input v-model="identifyCode" class="inpWidth" placeholder="4位数字验证码" />
                            <el-button type="primary" @click="getIdentifyCode(phone)" plain class="flex-button">
                                获取验证码
                            </el-button>
                        </el-row>
                    </el-form-item>
                    <el-row>
                        <el-checkbox class="checkBox" v-model="rAgree" label="同意用户使用准则" name="type" />
                    </el-row>
                    <el-button v-if="rAgree" type="primary" class="loginBtn lb" @click="register"
                        style="width: 310px;text-align: center;">
                        登录
                    </el-button>
                </el-form>
            </el-tab-pane>
        </el-tabs>
    </div>
    <!-- 忘记密码弹窗 -->
    <teleport to="body">
        <el-dialog v-model="isChangePassword" title="修改密码" width="25%">
            <el-form label-position="right" label-width="100px" style="max-width: 460px" class="loginForm">
                <el-form-item label="密码：">
                    <el-input type="password" v-model="uPassword" placeholder="请输入密码" @blur="judgepsd(uPassword)"
                        style="width: 250px;" />
                </el-form-item>
                <el-form-item label="确认密码：">
                    <el-input type="password" v-model="uconfirmPassword" @blur="updatepsdfirmFunc" placeholder="请再次输入密码"
                        style="width: 250px;" />
                </el-form-item>
                <el-form-item label="手机：" style="width: 350px;">
                    <el-input v-model="uphone" placeholder="请输入用户绑定的手机号" />
                </el-form-item>
                <el-form-item label="验证码：">
                    <el-row>
                        <el-input v-model="uidentifyCode" class="inpWidth" placeholder="4位数字验证码" />
                        <el-button type="primary" @click="getIdentifyCode(uphone)" plain>
                            获取验证码
                        </el-button>
                    </el-row>
                </el-form-item>

                <el-row>
                    <el-checkbox class="checkBox" v-model="rAgree" label="同意用户使用准则" name="type" />
                </el-row>
                <el-button v-if="rAgree" type="primary" class="loginBtn" @click="changePassword">
                    修改
                </el-button>
                <el-button v-if="rAgree" type="primary" class="loginBtn" @click="isChangePassword = false">
                    取消
                </el-button>
            </el-form>
        </el-dialog>
    </teleport>
    <!-- 注册弹窗 -->
    <teleport to="body">
        <el-dialog v-model="registerUser" title="用户注册" width="25%">
            <el-form label-position="right" label-width="100px" style="max-width: 360px" class="loginForm">
                <el-form-item label="用户名：" style="width: 350px;">
                    <el-input v-model="reusername" placeholder="请输入用户名" @blur="judgereuname(reusername)" />
                </el-form-item>
                <el-form-item label="密码：">
                    <el-input type="password" v-model="repassword" placeholder="请输入密码" @blur="judgepsd(repassword)"
                        style="width: 250px;" />
                </el-form-item>
                <el-form-item label="确认密码：">
                    <el-input type="password" v-model="rerePassword" @blur="repsdfirmFunc" placeholder="请再次输入密码"
                        style="width: 250px;" />
                </el-form-item>
                <el-form-item label="手机：" style="width: 350px;">
                    <el-input v-model="rephone" placeholder="请输入用户绑定的手机号" />
                </el-form-item>
                <el-form-item label="验证码：">
                    <el-row>
                        <el-input v-model="reuidentifyCode" class="inpWidth" placeholder="4位数字验证码" />
                        <el-button type="primary" @click="getreIdentifyCode(rephone)" plain>
                            获取验证码
                        </el-button>
                    </el-row>
                </el-form-item>
                <el-row>
                    <el-checkbox class="checkBox" v-model="rAgree" label="同意用户使用准则" name="type" />
                </el-row>
                <el-button v-if="rAgree" type="primary" class="loginBtn" @click="submitInfo">
                    注册
                </el-button>
                <el-button v-if="rAgree" type="primary" class="loginBtn" @click="registerUser = false">
                    取消
                </el-button>
            </el-form>
        </el-dialog>
    </teleport>
  </div>
  <background/>
</template>
<script>
import { reactive, toRefs, ref } from "@vue/reactivity";
import { ElMessage } from "element-plus";
import axios from '../../api/index';
import router from '@/router';
import Background from "@/components/parentComponents/Background.vue";
import AdminLog from "@/components/AdminLog.vue";

//   手机号验证方式
var phoneReg = /(^1\d{10}$)|(^[0-9]\d{7}$)/;
//   用户名验证正则
var reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$/;

const token = 'token';
const longtoken = 'longtoken';

export default {
  components: {AdminLog, Background},
    setup() {
        const form = reactive({
            account: "",
            password: "",
            isAgree: 0,
        });
        const registerForm = reactive({
            phone: "",
            identifyCode: "",
            rAgree: 0,
        });
        const updatepsdForm = reactive({
            uphone: "",
            uPassword: "",
            uconfirmPassword: "",
            uidentifyCode: "",
            rAgree: 0,
        });
        const registerUserForm = reactive({
            reusername: "",
            rephone: "",
            repassword: "",
            rerePassword: "",
            reuidentifyCode: "",
            rAgree: 0,
        });
        // 方法
        // 登录 将账号密码写入后台,获取用户数据,后登录
        // 需要修改共享数据
        function login() {

            judgeunph(form.account);
            if (actz === true) {
                judgepsd(form.password);
                if (psdyz === true) {
                    axios.get('/user/login?username=' + form.account + '&userPassword=' + form.password)
                        .then(response => {
                            console.log(form.account);
                            console.log(form.password);
                            console.log(response.code);
                            console.log(response.data);
                            console.log(response.code === 200);
                            if (response.code === 200) {
                                //存入长短token
                                localStorage.setItem(token, response.data.token);
                                localStorage.setItem(longtoken, response.data.longToken);
                                //该用户全部信息存入到localStorage中
                                localStorage.setItem('userInfo', JSON.stringify(response.data));
                                // 设置默认的请求头，将JWT令牌添加到Authorization字段中
                                axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem(token)}`;
                                ElMessage.success("登录成功~~");
                                router.push('/index');
                            } else {
                                ElMessage.error("密码错误~~");
                            }
                        })
                        .catch(function (error) {
                            ElMessage.error("服务器端错误~~");
                        })
                }
            }
        }
        // 注册 -- 将账号密码写入后台, 自动登录
        // 需要修改共享数据
        function register() {

            //先判断手机号是否合法
            if (!phoneReg.test(registerForm.phone)) {
                ElMessage.error("请输入正确的手机号");
            } else {
                //发起请求将手机号和验证码发送去后端判断，验证通过的话跳转界面，不通过的话进行提示
                
                axios.get('/user/phoneLogin?phone=' + registerForm.phone + "&inputCode=" + registerForm.identifyCode)
                    .then(response => {
                        if (response.code == 206) {
                            //存入长短token
                            localStorage.setItem(token, response.data.token);
                            localStorage.setItem(longtoken, response.data.longToken);
                            //该用户全部信息存入到localStorage中
                            localStorage.setItem('userInfo', JSON.stringify(response.data));
                            // 设置默认的请求头，将JWT令牌添加到Authorization字段中 
                            axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem(token)}`;
                            ElMessage.success("登录成功~~");
                            //跳转
                            router.push('/index');
                        } else if (response.code == 406 || response.code == 406) {
                            ElMessage.error("验证码有误~~");
                        } else if (response.code == 408) {
                            ElMessage.error("手机号与验证码匹配有误~~");
                        } else {
                            ElMessage.error("登录失败~~");
                        }
                    })
                    .catch(function () {
                        ElMessage.error("服务器端错误~~");
                    })
                console.log("注册", registerForm);
            }
        }
        // 获取登录验证码
        function getIdentifyCode(phone) {
            if (!phoneReg.test(phone)) {
                ElMessage.error("请输入正确的手机号");
            } else {
                //发起请求过去验证码,如果手机号在数据库中存在证明该手机号已经注册，可以发送验证码，如果不存在证明该手机号没有注册过不能够发验证码
                axios.get('/user/findPhone?phone=' + phone)
                    .then(response => {
                        if (response.code === 200) {
                            //手机号存在，可以发送验证码
                            axios.get('/sms?phone=' + phone)
                                .then(response => {
                                    if (response.code === 2000) {
                                        ElMessage.success("验证码发送成功，请在一分钟之内验证~~");
                                    } else if (response.code === 4000) {
                                        ElMessage.error("验证码发送失败~~");
                                    } else {
                                        ElMessage.error("服务器端错误~~");
                                    }
                                })
                                .catch(function (error) {
                                    ElMessage.error("服务器端错误~~");
                                })
                        } else if (response.code === 411) {
                            //手机号不存在，不可以发送验证码
                            ElMessage.error("该手机号未注册~~");
                        }
                    })
                    .catch(function (error) {
                        ElMessage.error("服务器端错误~~");
                    })
            }
        }
        // 获取注册验证码
        function getreIdentifyCode(phone) {
            if (!phoneReg.test(phone)) {
                ElMessage.error("请输入正确的手机号");
            } else {
                //发起请求过去验证码,如果手机号在数据库中存在证明该手机号已经注册，不可以再次进行注册，如果不存在证明该手机号没有注册则可以发送验证码进行注册
                axios.get('/user/findPhone?phone=' + phone)
                    .then(response => {
                        console.log(response.code);
                        console.log(response.code === 200);
                        if (response.code === 200) {
                            //手机号存在，不可以发送验证码
                            ElMessage.error("该手机号已经注册~~");
                        } else if (response.code === 411) {
                            //手机号不存在，可以发送验证码
                            axios.get('/sms?phone=' + phone)
                                .then(response => {
                                    if (response.code === 2000) {
                                        ElMessage.success("验证码发送成功，请在一分钟之内验证~~");
                                    } else if (response.code === 4000) {
                                        ElMessage.error("服务器端错误~~");
                                    }
                                })
                                .catch(function (error) {
                                    ElMessage.error("服务器端错误~~");
                                })
                        }
                    })
                    .catch(function (error) {
                        ElMessage.error("服务器端错误~~");
                    })
            }
        }

        // 确认密码
        const updatepsdfirmFunc = () => {
            if (updatepsdForm.uconfirmPassword !== updatepsdForm.uPassword)
                ElMessage.error("密码与确认密码不一致.");
        };
        // 确认注册密码
        const repsdfirmFunc = () => {
            if (registerUserForm.repassword !== registerUserForm.rerePassword)
                ElMessage.error("密码与确认密码不一致.");
        };
        //验证账户
        let actz = false;
        function judgeunph(account) {
            if (!phoneReg.test(account) && (!reg.test(account) || account.length < 6 || account.length > 12)) {
                ElMessage.error("请输入6-12位组合用户名或者正确手机号");
                actz = false;
            } else {
                actz = true;
            }
        }
        //验证注册用户名
        let acreun = false;
        function judgereuname(reusername) {
            if (!reg.test(reusername) || reusername.length < 6 || reusername.length > 12) {
                ElMessage.error("请输入6-12位组合用户名");
                acreun = false;
            } else {
                acreun = true;
            }
        }
        //验证密码
        let psdyz = false;
        function judgepsd(psd) {
            if (!reg.test(psd) || psd.length < 6 || psd.length > 12) {
                ElMessage.error("请输入6-12位数字字母组合密码");
                psdyz = false;
            } else {
                psdyz = true;
            }
        }
        // 修改密码
        let registerUser = ref(false);
        // 修改密码
        let isChangePassword = ref(false);
        // 修改密码时的密码参数
        function changePassword() {

            if (!reg.test(updatepsdForm.uPassword) || updatepsdForm.uPassword.length < 6 || updatepsdForm.uPassword.length > 12 ) {
                    ElMessage.error("请输入6-12位组合密码");
            } else if  (!phoneReg.test(updatepsdForm.uphone)) {
                ElMessage.error("请输入正确的手机号");
                //将数据传入后端进行判断如果手机号不一致的话则返回不同的数据
            } else if (updatepsdForm.uidentifyCode == '' || updatepsdForm.uidentifyCode == undefined || updatepsdForm.uidentifyCode == null) {
                ElMessage.error("请输入验证码");
            } else if (updatepsdForm.uconfirmPassword !== updatepsdForm.uPassword) {
                ElMessage.error("密码与确认密码不一致.");
            } else {
                axios({
                    method: 'PUT',
                    url: '/user/updatePsd',
                    data: JSON.stringify({
                        userPassword: updatepsdForm.uPassword,
                        phone: updatepsdForm.uphone,
                        codeStr: updatepsdForm.uidentifyCode
                    }),
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }).then(response => {
                    console.log(response);
                    console.log(response.code);
                    if (response.code === 200) {
                        ElMessage.success("修改成功~~");
                        location.reload();
                    } else if (response.code === 411) {
                        ElMessage.error("验证码错误~~");
                    } else {
                        ElMessage.error("修改失败~~");
                    }
                }, error => {
                    ElMessage.error("服务器端错误~~");
                })
            }
        }
        function submitInfo() {
            if (registerUserForm.reusername == '' || registerUserForm.reusername == undefined || registerUserForm.reusername == null) {
                ElMessage.error("请输入6-12位组合用户名");
            } else if (registerUserForm.repassword == '' || registerUserForm.repassword == undefined || registerUserForm.repassword == null) {
                ElMessage.error("请输入密码");
            } else if (registerUserForm.rerePassword == '' || registerUserForm.rerePassword == undefined || registerUserForm.rerePassword == null) {
                ElMessage.error("请输入确认密码");
            } else if (registerUserForm.rephone == '' || registerUserForm.rephone == undefined || registerUserForm.rephone == null
                || (!phoneReg.test(registerUserForm.rephone))) {
                ElMessage.error("请输入正确的手机号");
            } else if (registerUserForm.reuidentifyCode == '' || registerUserForm.reuidentifyCode == undefined || registerUserForm.reuidentifyCode == null) {
                ElMessage.error("请输入验证码");
            } else if (registerUserForm.repassword !== registerUserForm.rerePassword) {
                ElMessage.error("两次密码输入不一致");
            } else {
                axios({
                    method: 'POST',
                    url: '/user/register',
                    data: JSON.stringify({
                        username: registerUserForm.reusername,
                        userPassword: registerUserForm.repassword,
                        phone: registerUserForm.rephone,
                        codeStr: registerUserForm.reuidentifyCode
                    }),
                    headers: {
                        'Content-Type': 'application/json',
                        // 'Authorization': `Bearer ${longtoken} ${token}`
                    }
                }).then(response => {
                    if (response.code === 201) {
                        ElMessage.success("注册成功~~");
                        location.reload();
                    } else if (response.code === 401) {
                        ElMessage.error("验证码错误~~");
                    } else {
                        ElMessage.error("注册失败~~");
                    }
                }, error => {
                    ElMessage.error("服务器端错误~~");
                })
            }
        }

        return {
            registerUser,
            isChangePassword,
            ...toRefs(form),
            ...toRefs(registerForm),
            ...toRefs(updatepsdForm),
            ...toRefs(registerUserForm),
            login,
            register,
            getIdentifyCode,
            updatepsdfirmFunc,
            changePassword,
            judgeunph,
            judgepsd,
            judgereuname,
            repsdfirmFunc,
            getreIdentifyCode,
            submitInfo,
        };
    },
};
</script>
  
<style scoped>
#log {
  width: 80vw;
  height: 100vh;
}
.layout {
    position: absolute;
    left: calc(44% - 200px);
    top: 20%;
    width: 600px;
    height: 400px;
    border-radius: 15px;
    font-size: 36px;
    opacity: 0.9;
}
.card {
  left: -10px;
  width: 100%;
  height: 100%;
  border-radius: 15px;
  height: 400px;
  width: 600px;
}
.input {
  width: 300px;
}

.loginBtn {
    width: 100px;
    border-radius: 15px;
    letter-spacing: 10px;
}

.loginForm {
    text-align: center;
}

.checkBox {
    margin-left: 7px;
  font-size: 16px;
}

.inpWidth {
    width: 148px;
}

.floatR {
    font-size: 18px;
    margin: 0 auto;
    color: rgb(255, 0, 0);
}
.logcard {
  margin: 25px;
}

.lb {
  margin-left: 43px;
  margin-top: 50px;
}

.flex-button {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 85px;


}
</style>
  